// const BASE_URL = 'http://localhost:8001';
// const BASE_URL = 'http://182.92.215.229:8001';
const BASE_URL = 'https://hot-tomato.top:9001';
//   //'https://xiaodu.cyclecenturycloud.com:8389';  
import { useUserStore } from '@/stores/user'

const request = (options)=>{
	const {url,method='GET',data={},headers={}} = options;
	const token = uni.getStorageSync('token');
	const defaultHeaders = {
		'Content-Type':'application/json',
		'Authorization':token ? token : ''		
	}
	return new Promise((resolve,reject)=>{
		uni.request({
			url:`${BASE_URL}${url}`,
			method,
			data,
			header:{...defaultHeaders,...headers},
			success:res=>{
				console.log('request success res',res);
				if (res.statusCode === 200){
					if ( res.data?.code === 1000 ){
						resolve(res.data);
					} else if (res.data?.code === 401) {
						// token失效，调用处理函数
						const userStore = useUserStore()
						userStore.handleTokenExpired()
						reject(new Error('登录已过期，请重新登录'))
					} else {
						reject(new Error(res.data?.message || '请求失败'));
					}
				} else if (res.statusCode === 401){
					// token失效，调用处理函数
					const userStore = useUserStore()
					userStore.handleTokenExpired()
					reject(new Error('登录已过期，请重新登录'))
				} else {
					reject(res);
				}
			},
			fail:err=>{
				console.log('uni.request err',err)
				reject(err)
			}
		})
	})
}

const uploadFile = (filePath) => {
	const token = uni.getStorageSync('token');
	return new Promise((resolve,reject)=>{
		uni.uploadFile({
			url: `${BASE_URL}/app/user/comm/upload`,
			filePath:filePath,
			name: 'file',
			header: {
				'Authorization':token ? token : ''	
			},	
			success: (res) => {
				if (res.statusCode === 200){
					console.log('uploadFile res.data?.code',res.data?.code);
					const data  = JSON.parse(res.data);
					if ( data?.code === 1000 ){
						resolve(data);
					} else if (data?.code === 401) {
						// token失效，调用处理函数
						const userStore = useUserStore()
						userStore.handleTokenExpired()
						reject(new Error('登录已过期，请重新登录'))
					} else {
						reject(new Error(data?.message || '请求失败'));
					}
				} else if (res.statusCode === 401){
					// token失效，调用处理函数
					const userStore = useUserStore()
					userStore.handleTokenExpired()
					reject(new Error('登录已过期，请重新登录'))
				} else {
					reject(res);
				}
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

export default request;
export {uploadFile};